package org.muxiao.seckill.config;

import org.muxiao.seckill.pojo.User;
import org.muxiao.seckill.service.UserService;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

/**
 * UserArgumentResolver: 自定义一个方法参数解析器
 * 判断当前要解析的参数类型是不是User类型,
 * 如果是, 就从cookie中获取用户信息, 并封装到User对象中返回
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private UserService userService;

    /**
     * 判断当前要解析的参数类型是不是你需要的类型
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //获取参数是不是user类型
        Class<?> aClass = methodParameter.getParameterType();
        //如果为t, 就执行resolveArgument
        return aClass == User.class;
    }

    /**
     * 如果上面supportsParameter,返回T,就执行resolveArgument方法
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        //
        //String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //if (StringUtils.isBlank(ticket)) {
        //    return null;
        //}
        //
        //User user = userService.getUserByCookie(ticket, request, response);
        //
        //return user;

        return UserContext.getUser();
    }
}
